package com.common.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.common.util.FormatUtil;
import com.common.util.HttpUtil;
import com.demo.common.model.Stock;
import com.demo.common.model._MappingKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;

/**
 * 获取股票代码
 * */
public class GetStockCodeJob implements Job {

	private static final Log log = Log.getLog(GetStockCodeJob.class);
	
	private static final int RETRY_TIMES = 3;
	
	@Override
	public void execute(JobExecutionContext job) throws JobExecutionException {
		long startTime = System.currentTimeMillis();
		log.info("开始更新股票列表信息:" + FormatUtil.formatDate(new Date()));
		if (getStockCode()) {
			long endTime = System.currentTimeMillis();
			log.info("更新完毕:" + FormatUtil.formatDate(new Date()) + ";耗时:" + ((endTime-startTime)/1000));
		} else {
			log.error("更新失败!");
		}
	}
	
	private boolean getStockCode() {
		try {
			Document document = null;
			for(int i = 0; i < RETRY_TIMES; i++) {
				try {
					document = HttpUtil.getDocumentByGet("http://quote.eastmoney.com/stocklist.html");
					Elements liList = document.select("div#quotesearch > ul > li");
					Iterator<Element> liInterator = liList.iterator();
					
					List<Stock> stockList = new ArrayList<Stock>();
					
					while(liInterator.hasNext()) {
						Element element = liInterator.next();
						String stockStr = element.text();
                        String stocknum=stockStr.substring(stockStr.indexOf("(") + 1, stockStr.length() - 1);
						if((stocknum.startsWith("0")||stocknum.startsWith("6")||(stocknum.startsWith("3")))&&null == Stock.dao.findByCode(stocknum)) {
							Stock stock = new Stock();
							stock.setStockCode(stockStr.substring(stockStr.indexOf("(") + 1, stockStr.length() - 1));
							stock.setStockName(stockStr.substring(0, stockStr.indexOf("(")));
							stock.setStockUrl(element.select("a").first().attr("href"));
							if(stock.getStockUrl().indexOf("sz") != -1) {
								stock.setStockCode("sz" + stock.getStockCode());
							} else {
								stock.setStockCode("sh" + stock.getStockCode());
							}
							stockList.add(stock);
						}
					}
					
					Stock.dao.batchSave(stockList);
					
					break;
				} catch(Exception e) {
					log.error("第" + (i + 1) + "次请求股票列表失败!3秒后重新尝试:" + e.getMessage(), e);
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						log.error("下载股票列表线程发生错误：" + e.getMessage(), e);
						e1.printStackTrace();
					}
				}
			}
			if (document == null) {
				throw new IllegalArgumentException("获取股票列表失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return false;
		}
		return true;
	}
	
	public static void main(String[] args) {
		DruidPlugin dp = new DruidPlugin("jdbc:mysql://127.0.0.1/jfinal_stock?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull", "root", "root");
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
		_MappingKit.mapping(arp);
		// 与web环境唯一的不同是要手动调用一次相关插件的start()方法
		dp.start();
		arp.start();
		new GetStockCodeJob().getStockCode();
	}

}